const router = require("koa-router")()

router.prefix("/port")

const {CtxBody, PageSize, ServerUrl } = require("../models/config")

const hotSearch = require("../models/HotSearch")

var { Goods, GoodsMain, GoodsGuide, GoodsFirstClass, GoodsSecondClass } = require("../models/goods")

var { User } = require("../models/users")

var { Info, InfoClass} = require("../models/info")

const { upload }  = require("../models/multer")

const { APPID, SECRET_KEY, SecretKey,expiresIn } = require("../models/config")

const { Profile, OffMessage } = require("../models/profile")

const axios = require("axios")

const jwt = require("jsonwebtoken")

// 解密中间件
var WXBizDataCrypt = require('../util/wxCrypt')


// 小程序前端回去openid

router.post("/getopenid", async ctx => {
    let { code } = ctx.request.body
    console.log(code);
    
    if (code) {
        let res = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET_KEY}&js_code=${code}&grant_type=authorization_code`)
        // let errcode = res.data.code
        // console.log(res.data);
        
        if (res.data) {
            CtxBody(ctx, 200, res.data)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 小程序使用openid获取token

router.post("/getUserToken", async ctx => {
    let { openid } = ctx.request.body
    if (openid) {
        let user = await User.findOne({ openid })
        if (user) {
            let payload = {
                id: user._id
            }
            let token = await jwt.sign(payload, SecretKey, { expiresIn })
            CtxBody(ctx, 200, token)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 解密微信数据

router.post("/getSecretData", async ctx => {
    let { encryptedData, iv ,sessionKey } = ctx.request.body
    var pc = new WXBizDataCrypt(APPID, sessionKey)

    var data = pc.decryptData(encryptedData , iv)
    if (data) {
        CtxBody(ctx, 200, data)
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 小程序 获取信息分类

router.post("/getInfoClass", async ctx => {
    let res = await InfoClass.find({status: "1"})
    if (res) {
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 根据分类ID 获取信息

router.post("/getAllInfoByID", async ctx => {
    let { id } = ctx.request.body 
    if (id) {
        let res = await InfoClass.findOne({ _id: id },"InfoList").populate({
            path:"InfoList",
            populate: "sendBy"
        })
        if (res) {
            CtxBody(ctx, 200, res)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 上传文件返回地址
router.post("/uploadImage", upload.single("contentimage"), async ctx => {
        let filename = ctx.req.file.filename
        if (filename) {
            let image = `${ServerUrl}/public/uploads/${filename}`
            CtxBody(ctx, 204, image)
        } else {
            CtxBody(ctx, 304, "")
        } 
})

// 小程序获取所有的医生

router.post("/getAllDoctors", async ctx => {
    let res = await User.find({ role: "2", status: "1"})
    if (res) {
        CtxBody(ctx, 200, res)
    } else {
        CtxBody(ctx, 404, "")
    }
})


// 小程序根据id获取用户信息

router.post("/getUserInfoByID", async ctx => {
    let  { id } = ctx.request.body
    if (id) {
        let user = await User.findOne({ _id: id }, "_id nickname avatar")
        if (user) {
            CtxBody(ctx, 200, user)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 添加聊天数据

router.post('/addmsg', async ctx => {
    const profileFields = {};
    let { target, user_id , count, message } = ctx.request.body 
    // 判断用户是否存在
    let user = await Profile.findOne({ target, user_id})
    if (user) {
        user.message = message;
        user.count = count;
        let ret = await user.save()
        CtxBody(ctx, 200, ret)
    } else {
       
                let file = new Profile({
                    user_id,
                    count,
                    message,
                    target,
                    user: user_id
                })
                let ress = await file.save()
                CtxBody(ctx, 202, ress)
    }
})

// 获取用户端聊天记录

router.post('/getMessageList', async ctx => {
    let { id } = ctx.request.body 
    let pro = await Profile.find({ user_id: id })
    if (pro.length) {
        
       CtxBody(ctx, 200, pro)
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 保存离线信息

router.post("/saveOffMessage", async ctx => {
    let { target, current, msg } = ctx.request.body 
    if (target && current && msg ) {
        let newmsg = new OffMessage({
            target,
            msg,
            current,
            status: "1"
        })
        let res = await newmsg.save()
        CtxBody(ctx, 202, "")
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 查看是否有连线信息

router.post("/getOffMessage", async ctx => {
    let { id } = ctx.request.body 
    if (id) {
        let res = await OffMessage.find({ target: id, status:"1" })
        if (res.length) {
            CtxBody(ctx, 200, res)
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 删除已经发送的离线消息

router.post("/deleteSend", async ctx => {
    let res = await OffMessage.deleteMany({ status: "2"})
    CtxBody(ctx, 200, "")
})

// 发送连线消息后改变状态

router.post("/changeOffMessageStatus", async ctx => {
    let { id } = ctx.request.body
    if(id) {
        let res = await OffMessage.findOneAndDelete({_id: id})
        CtxBody(ctx, 200, "")
    } else {
        CtxBody(ctx, 30003, "")
    }
})


// 更新count

router.post("/setCount", async ctx => {
    let { id } = ctx.request.body 
    if (id) {
        let res = await Profile.findOneAndUpdate({ _id: id}, {
            $inc: {
                count: 1
            }
        })
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 30003, "")
    }
})

// 更新聊天数据 


router.post("/addMessageList", async ctx => {
    let { user_id, target, msg} = ctx.request.body 
    console.log(msg)
    let data = {
    	msg: msg.msg,
    	source:"other"
    }
    let res = await Profile.findOneAndUpdate({ "target._id": target, user_id, }, {
    	$push: {
    		message: data
    	}
    })
    if (res) {
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 404, "")
    }
})


// count 归零

router.post("/setCountZero",async ctx => {
    let { id } = ctx.request.body 
    if (id) {
        let res = await Profile.findOneAndUpdate({ user_id: id}, {
            $set: {
                count: 0
            }
        })
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 30003, "")
    }
})

module.exports = router